/*
 * Copyright (C) 2016  Nicola Spanti (RyDroid) <dev@nicola-spanti.info>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */


#include "PlanetWars2dRT-SDL2/specific/controller/game_playing.h"
#include "PlanetWars2dRT-SDL2/specific/controller/game_playing_data.h"
#include "PlanetWars2dRT-core/specific/controller/selection.h"
#include "PlanetWars2dRT-SDL2/specific/controller/game_frame_events.h"
#include "PlanetWars2dRT-SDL2/specific/view/draw_game_playing.h"
#include "PlanetWars2dRT-SDL2/utils/SDL.h"


EXTERN_C_BEGIN


bool
game_playing_sdl_do_if_not_paused(game_playing_t* a_game_playing)
{
  if(game_state_get_selection_state(&a_game_playing->state) == SELECTION_STATE_FINAL
     &&
     a_game_playing->state.selection.use_selection_to_move_ships)
    {
      selection_2d_uint_move_ships_of_player_index(&a_game_playing->game.universe,
						   &a_game_playing->state.selection.selection,
						   0 /* TODO fix magic value */,
						   &a_game_playing->state.selection.position_to_move_ships);
      game_state_clear_selection(&a_game_playing->state);
    }
  return SDL_draw_game_playing(a_game_playing);
}

void
game_playing_sdl_manage_framerate(game_playing_data_sdl* data)
{
  unsigned int new_time_ms = SDL_GetTicks();
  unsigned int time_ms_delta = new_time_ms - data->time_ms_last_frame;
  data->time_ms_last_frame = new_time_ms;
  if(time_ms_delta < data->time_ms_per_frame)
    {
      unsigned int time_ms_to_wait = data->time_ms_per_frame - time_ms_delta;
      data->time_ms_last_frame += time_ms_to_wait;
      SDL_Delay(data->time_ms_per_frame - time_ms_delta);
      data->frame_per_second = 1000 / data->time_ms_per_frame;
    }
  else
    {
      data->frame_per_second = 1000 / time_ms_delta;
    }
}

bool
game_playing_sdl_do_always(game_playing_t* a_game_playing)
{
  game_playing_sdl_manage_framerate(a_game_playing->data);
  game_frame_events_manager(&a_game_playing->state);
  return true;
}


EXTERN_C_END
